import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, Input, Select, Form, Modal, Typography, Space, Spin, Empty, Pagination, App } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { removeEmptyParams } from '../utils/removeEmptyParams';
import { get, postWithResponse } from '../utils/request';

const { Title } = Typography;

const sceneTypeOptions = [
  { label: '首次生成/再次生成', value: 'generate' },
  { label: '引用扩写', value: 'quote_extension' },
  { label: '输出格式', value: 'output_format' },
];

const SceneTemplateManager: React.FC = () => {
  const { message: messageApi } = App.useApp();
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editRecord, setEditRecord] = useState<any>(null);
  const navigate = useNavigate();

  // 查询与分页
  const fetchData = useCallback(async (params: any = {}) => {
    setLoading(true);
    setError('');
    try {
      const queryObj = removeEmptyParams({
        pageIndex: String(params.pageIndex),
        pageSize: String(params.pageSize),
        sceneType: params.sceneType,
        id: params.id,
      });
      const result = await get('/api/admin/template/scene/list', queryObj);
      if (result) {
        setData(result.list || []);
        setTotal(result.count || 0);
      } else {
        setData([]);
        setTotal(0);
        setError('获取数据失败');
      }
    } catch (e) {
      setData([]);
      setTotal(0);
      setError('网络异常，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData({ pageIndex: 1, pageSize });
  }, [fetchData, pageSize]);

  // 查询
  const handleSearch = () => {
    setCurrent(1);
    fetchData({
      pageIndex: 1,
      pageSize,
      ...form.getFieldsValue(),
    });
  };

  // 重置
  const handleReset = () => {
    form.resetFields();
    setCurrent(1);
    fetchData({ pageIndex: 1, pageSize });
  };

  // 分页
  const handleTableChange = useCallback((page: number, size?: number) => {
    setCurrent(page);
    setPageSize(size || pageSize);
    fetchData({
      pageIndex: page,
      pageSize: size || pageSize,
      ...form.getFieldsValue()
    });
  }, [fetchData, form, pageSize]);

  // 编辑操作
  const handleEdit = (record: any) => {
    setEditRecord(record);
    if (record) {
      editForm.setFieldsValue({
        sceneName: record.sceneName,
        sceneDesc: record.sceneDesc,
        sceneType: record.sceneType,
      });
    } else {
      editForm.resetFields();
    }
    setEditModalVisible(true);
  };

  const handleEditCancel = () => {
    setEditModalVisible(false);
    setEditRecord(null);
    editForm.resetFields();
  };

  // 保存
  const handleSave = async () => {
    try {
      const values = await editForm.validateFields();
      setLoading(true);
      const url = editRecord ? '/api/admin/template/scene/update' : '/api/admin/template/scene/create';
      const body = editRecord ? { ...values, id: editRecord.id } : values;
      const result = await postWithResponse(url, body);
      if (result.success) {
        messageApi.success(editRecord ? '更新成功！' : '创建成功！');
        handleEditCancel();
        fetchData({ pageIndex: current, pageSize });
      } else {
        messageApi.error(result.errorMsg || (editRecord ? '更新失败' : '创建失败'));
      }
    } catch (e) {
      if (e instanceof Error) {
        messageApi.error('表单验证失败，请检查输入');
      }
    } finally {
      setLoading(false);
    }
  };

  // 删除操作
  const handleDelete = async (id: number) => {
    try {
      await Modal.confirm({
        title: '确认删除',
        content: '确定要删除这个场景吗？删除后不可恢复。',
        okText: '确认',
        cancelText: '取消',
        okButtonProps: { danger: true },
      });
      
      setLoading(true);
      const result = await postWithResponse('/api/admin/template/scene/delete', { id });
      if (result.success) {
        messageApi.success('删除成功！');
        fetchData({ pageIndex: current, pageSize });
      } else {
        messageApi.error(result.errorMsg || '删除失败');
      }
    } catch (e) {
      if (e instanceof Error) {
        messageApi.error('网络异常，删除失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    { title: '场景名称', dataIndex: 'sceneName', key: 'sceneName', width: '30%' },
    { title: '场景类型', dataIndex: 'sceneType', key: 'sceneType', width: '25%', render: (v: string) => {
      const t = sceneTypeOptions.find(opt => opt.value === v); return t ? t.label : v;
    } },
    { title: '场景描述', dataIndex: 'sceneDesc', key: 'sceneDesc', width: '25%' },
    { title: '操作', key: 'action', width: '20%', render: (_: any, record: any) => (
      <Space size="small">
        <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
          编辑
        </Button>
        <Button 
          type="link" 
          size="small"
          danger 
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </Space>
    ) },
  ];

  return (
    <div style={{ 
      background: '#fff', 
      padding: '0px 8px',
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      overflow: 'hidden'
    }}>
      <Title level={5} style={{ textAlign: 'left', margin: '12px 0', fontWeight: 600, fontSize: 18 }}>场景管理</Title>
      <Spin spinning={loading} tip="加载中...">
        {error && <div style={{ color: 'red', marginBottom: 16 }}>{error}</div>}
        <Form form={form} layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item name="sceneType" label="场景类型">
            <Select
              placeholder="请选择场景类型"
              style={{ width: 200 }}
              options={sceneTypeOptions}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleSearch} loading={loading}>查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset} disabled={loading}>重置</Button>
          </Form.Item>
        </Form>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
          <Button type="primary" onClick={() => handleEdit(null)}>新增</Button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            pagination={false}
            scroll={{ y: 'calc(100vh - 280px)' }}
            bordered
            locale={{ emptyText: error ? <Empty description={error} /> : <Empty description="暂无数据" /> }}
            style={{ width: '100%' }}
            size="middle"
          />
        </div>
        <div style={{ 
          marginTop: 16, 
          display: 'flex', 
          justifyContent: 'flex-end',
          width: '100%'
        }}>
          <Pagination
            current={current}
            pageSize={pageSize}
            total={total}
            onChange={(page, size) => handleTableChange(page, size)}
            showSizeChanger
            pageSizeOptions={[5, 10, 20, 50]}
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            locale={{
              items_per_page: '条/页',
              jump_to: '跳至',
              jump_to_confirm: '确定',
              page: '页',
              prev_page: '上一页',
              next_page: '下一页',
              prev_5: '向前 5 页',
              next_5: '向后 5 页',
              prev_3: '向前 3 页',
              next_3: '向后 3 页',
            }}
          />
        </div>
      </Spin>
      <Modal
        title={editRecord ? '编辑场景' : '新增场景'}
        open={editModalVisible}
        onCancel={handleEditCancel}
        onOk={handleSave}
        confirmLoading={loading}
        maskClosable={false}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={editForm}
          layout="vertical"
        >
          <Form.Item
            label="场景名称"
            name="sceneName"
            rules={[{ required: true, message: '请输入场景名称' }]}
          >
            <Input placeholder="请输入场景名称" />
          </Form.Item>
          <Form.Item
            label="场景类型"
            name="sceneType"
            rules={[{ required: true, message: '请选择场景类型' }]}
          >
            <Select
              options={sceneTypeOptions}
              placeholder="请选择场景类型"
            />
          </Form.Item>
          <Form.Item
            label="场景描述"
            name="sceneDesc"
          >
            <Input.TextArea
              placeholder="请输入场景描述"
              rows={4}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SceneTemplateManager; 